import json
import time
import requests
from quant_researcher.quant.project_tool.time_tool import timestamp_to_str
import pandas as pd


def fetch_okex_usdtcny_premium():
    """
    从https://www.okx.com/markets/data-list 获取USDT场外兑CNY折溢价数据

    :return:
    """

    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}
    timestamp_ = int(time.time() * 1000)
    datetime_ = timestamp_to_str(timestamp_/1000, fmt='%Y-%m-%d %H:%M:%S', tz_str='+0000')
    date_ = timestamp_to_str(timestamp_/1000, fmt='%Y-%m-%d', tz_str='+0000')

    ticker_url = f'https://www.okx.com/v3/c2c/otc-ticker?t={timestamp_}&baseCurrency=USDT&quoteCurrency=CNY'
    orderbook_url = f'https://www.okx.com/v3/c2c/tradingOrders/books?t={timestamp_}&quoteCurrency=cny&baseCurrency=usdt&side=all' \
                    f'&paymentMethod=all&userType=all&showTrade=false&receivingAds=false&showFollow=false&showAlreadyTraded=false&isAbleFilter=false'

    res1 = requests.get(ticker_url, headers=header, timeout=30)
    df_ticker = pd.DataFrame(json.loads(res1.content)['data'], index=[0])
    df_ticker.rename(columns={'otcTicker': 'usdtcny'}, inplace=True)
    df_ticker['usdtcny'] = df_ticker['usdtcny'].astype(float)
    df_ticker['timestamp'] = timestamp_
    df_ticker['datetime'] = datetime_
    df_ticker['date'] = date_

    res2 = requests.get(orderbook_url, headers=header, timeout=30)
    df_buy = pd.DataFrame(json.loads(res2.content)['data']['sell'])  # 这里的数据正好是相反的
    df_sell = pd.DataFrame(json.loads(res2.content)['data']['buy'])
    df_orderbook = pd.concat([df_buy, df_sell], axis=0)
    df_orderbook.rename(columns={'price': 'usdtcny'}, inplace=True)
    df_orderbook['usdtcny'] = df_orderbook['usdtcny'].astype(float)
    df_orderbook['timestamp'] = timestamp_
    df_orderbook['spread'] = (df_buy['price'].astype(float).min() - df_sell['price'].astype(float).max()) / df_sell['price'].astype(float).max()
    df_orderbook['datetime'] = datetime_
    df_orderbook['date'] = date_

    return df_ticker, df_orderbook


if __name__ == '__main__':
    fetch_okex_usdtcny_premium()